import Cookie from 'js-cookie'
import Vue from 'vue'
import bus from '../plugins/bus'
import * as pathConfig from './config'

// import VueI18n from 'vue-i18n'
import {
  Message
} from 'element-ui';

export default function ({ $axios, query}) {
  $axios.onRequest(config => {
    if (config.url == '/p/file/uploadImFile'){
      config.headers['Content-Type'] = 'multipart/form-data;'
    } else if (config.url == '/p/user/recentBrowse') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    else {
      config.headers['Content-Type'] = 'application/json; charset=utf-8'
    }
    let lang = null
    if (query.lang) {
      Cookie.set('language', query.lang)
      lang = query.lang
    } else if (Cookie.get('language')) {
      lang = Cookie.get('language')
    } else {
      Cookie.set('language',process.env.LANGUAGE ? process.env.LANGUAGE : 'zh')
      lang = process.env.LANGUAGE ? process.env.LANGUAGE : 'zh'
    }
    config.headers['Accept-Language'] = lang
    var token = Cookie.get('token')
    if (token && (config.url.indexOf("/p/") === 0 || config.url == '/user/registerOrBindUser')) {
      config.headers['Authorization'] = 'bearer' + token
    }
    if (config.url.indexOf('/p/user/conversations') === 0  || config.url == '/p/user/recentBrowse'){
      config.url = pathConfig.imPath + config.url
    }else{
      config.url = pathConfig.path + config.url
    }
  })

  $axios.onError(error => {
    const code = parseInt(error.response.status)
    if (code == 400) {
      Message.warning(error.response.data)
    } else if (code == 500) {
      Message.error('服务器出了点小差~')
    } else if (code == 401) {
      var url = error.response.config.url;
      Cookie.remove('token')
      if (url === pathConfig.path + '/p/user/collection/isCollection' || url === pathConfig.path + '/p/shop/collection/isCollection') {
        return
      } else {
        bus.$emit("showLogin", true)
      }
      // Message.warning('请先登录')
      //redirect('/login')
    } else if (code == 204) {
      Message.error('活动已结束！')
      this.$router.push({ path: '/index' })
      return
    }
  })
}
